#include "stdafx.h"

Control * Scene::find_control(int x, int y)
{
	for (int i = cs.size() - 1; i >= 0; i--)
	{
		if (cs[i]->in(x, y))
		{
			return cs[i];
		}
	}

	return nullptr;
}

Scene::Scene()
{
}

void Scene::draw(Gdiplus::Graphics & graphics)
{
	graphics.Clear(0xffffffff);

	for (int i = 0; i < gs.size(); i++)
	{
		gs[i]->draw(graphics);
	}
}

void Scene::LButtonDown(int x, int y)
{
	
	Control * ctl = find_control(x, y);
	Control * focused = find_focused();

	if (ctl)
	{
		ctl->LButtonDown(x, y);

		if (ctl != focused)
		{
			ctl->GetFocus();
			ctl->focused = true;
			if (focused)
			{
				focused->LostFocus();
				focused->focused = false;
			}
		}
	}
	else
	{
		if (focused)
		{
			focused->LostFocus();
			focused->focused = false;
		}
	}

	left_button_down(x, y);
}

void Scene::LButtonUp(int x, int y)
{
	Control * ctl = find_control(x, y);

	if (ctl)
	{
		ctl->LButtonUp(x, y);
	}

	left_button_up(x, y);
}

void Scene::RButtonDown(int x, int y)
{
	Control * ctl = find_control(x, y);

	if (ctl)
	{
		ctl->RButtonDown(x, y);
	}

	right_button_down(x, y);
}

void Scene::RButtonUp(int x, int y)
{
	Control * ctl = find_control(x, y);

	if (ctl)
	{
		ctl->RButtonUp(x, y);
	}

	right_button_up(x, y);
}

void Scene::MouseMove(int button, int x, int y)
{
	static Control * last = nullptr;

	Control * ctl = find_control(x, y);

	if (ctl && ctl == last || ctl && last == nullptr)
	{
		ctl->MouseMove(button, x, y);
	}
	else if (ctl && ctl != last || last && !ctl)
	{
		last->MouseLeave(button, x, y);
	}

	last = ctl;

	mouse_move(button, x, y);
}

void Scene::KeyDown(int keycode)
{
	Control * ctl = find_focused();

	if (ctl)
	{
		ctl->KeyDown(keycode);
	}

	key_down(keycode);
}

void Scene::KeyUp(int keycode)
{
	Control * ctl = find_focused();

	if (ctl)
	{
		ctl->KeyUp(keycode);
	}

	key_up(keycode);
}

void Scene::add_control(Control * ctl)
{
	ctl->graphics = graphics;
	cs.push_back(ctl);
	gs.push_back(ctl);
}

Control * Scene::find_focused()
{
	for (int i = 0; i < cs.size(); i++)
	{
		if (cs[i]->focused)
		{
			return cs[i];
		}
	}

	return nullptr;
}